'use strict'

const { Blog, Type, Op } = require('../model');

async function getAll(ctx, next) {
    let res;
    let keyword = ctx.request.query.keyword;
    let blogs = await Blog.findAll();
    let Typees = await Type.findAll();
    // console.log(Typees);
    blogs.forEach(item => {
        // console.log(item.dataValues);
        let arrType = Typees.filter(bj => {
            // console.log(bj.dataValues);
            return item.dataValues.typeId == bj.dataValues.id
        })
        // console.log(arrType);
        if (arrType.length > 0) {
            item.dataValues.typeName = arrType[0].dataValues.typename
        }
    })
    if (keyword) {
        res = blogs.filter(item => {
            // console.log(item);
            return item.dataValues.blogName.includes(keyword) || item.dataValues.typeName.includes(keyword)
        })
    } else {
        res = blogs
    }

    ctx.body = res;

}
async function getById(ctx, next) {
    let id = ctx.request.params.id;
    let data = await Blog.findByPk(id);

    ctx.body = {
        code: 1000,
        data: data,
        msg: '查询指定项目成功'
    }
}
async function addItem(ctx, next) {
    let obj = ctx.request.body;
    console.log(obj);
    let res = await Blog.create({
        blogName: obj.headline,
        typeId: obj.typeId,
        abstract:obj.abstract,
        content:obj.content,
        author:obj.author,
        time:obj.time
    })
    ctx.body = {
        code: 1000,
        data: res,
        msg: '新增成功'
    }
}
async function updateItem(ctx, next) {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    await Blog.update({ BlogName: obj.headline, TypeId: obj.TypeId,abstract:obj.abstract,content:obj.content,author:obj.author,time:obj.time }, {
        where: {
            id: id
        }
    });

    ctx.body = {
        code: 1000,
        data: null,
        msg: '修改成功'
    }
}
async function delItem(ctx, next) {
    let id = ctx.request.params.id;
    await Blog.destroy({
        where: {
            id: id
        }
    });
    ctx.body = {
        code: 1000,
        data: null,
        msg: '删除成功'
    }
}
// async function getAll(ctx, next) {


// }

module.exports = {
    'get /blogs': getAll,
    'get /blogs/:id': getById,
    'post /blogs': addItem,
    'put /blogs/:id': updateItem,
    'del /blogs/:id': delItem,
}